package com.hxzy.shop.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.ISelect;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hxzy.shop.dto.auth.req.MerchantListReq;
import com.hxzy.shop.dto.auth.req.MerchantRemarkReq;
import com.hxzy.shop.dto.auth.resp.MerchantInfoResp;
import com.hxzy.shop.dto.auth.resp.MerchantListResp;
import com.hxzy.shop.dto.auth.resp.MerchantResp;
import com.hxzy.shop.dto.mapstruct.MerchantConvert;
import com.hxzy.shop.entity.Business;
import com.hxzy.shop.entity.Merchant;
import com.hxzy.shop.entity.MerchantRemark;
import com.hxzy.shop.mapper.BusinessConfigMapper;
import com.hxzy.shop.mapper.MerchantMapper;
import com.hxzy.shop.mapper.MerchantRemarkMapper;
import com.hxzy.shop.service.MerchantService;
import com.hxzy.shop.vo.ApiException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @Author wy
 * @Description 商户实现
 * @Date 2023/5/6 16:59
 * @Version 1.0
 */
@Service
public class MerchantServiceImpl extends ServiceImpl<MerchantMapper, Merchant> implements MerchantService {


    @Autowired
    private MerchantMapper merchantMapper;

    /**
     * 商户备注
     */
    @Autowired
    private MerchantRemarkMapper merchantRemarkMapper;

    /**
     * 商户独立业务表(附加业务)
     */
    @Autowired
    private BusinessConfigMapper businessConfigMapper;

    @Override
    public PageInfo<MerchantListResp> getMerchantList(MerchantListReq req) {

        //排序 asc升序 desc降序
        if (ObjectUtil.isEmpty(req.getSortState())) {
            req.setSortState("desc");
        }else {
            req.setSortState("asc");
        }

        // 如果 没有设定  排序类型 1门店数量 2有效天数
        if (ObjectUtil.isEmpty(req.getSort())) {
            req.setSort(3);
        }

        //
        String sort = null;
        if (req.getSort() == 1) {
            //门店排序
            sort = "store_count";
        } else if (req.getSort() == 2) {
            // 有效天数(sql来计算出来虚拟列)
            sort = "effectiveTime";
        } else {
            // 激活时间
            sort = "activate_time";
        }

       // 拼出一个order by条件
        String orderBy=sort + " " +req.getSortState();

        // 写法1
        PageInfo<MerchantListResp> pageInfo = PageHelper.startPage(req.getPageNum(), req.getPageSize(), orderBy)
                .doSelectPageInfo(new ISelect() {
                    @Override
                    public void doSelect() {
                        merchantMapper.selectAllMerchant(req);
                    }
                });

//        // 写法2 （jdk8   lamdba 表达式）
//        PageInfo<MerchantListResp> pageInfo2 = PageHelper.startPage(req.getPageNum(), req.getPageSize(), orderBy)
//                .doSelectPageInfo(()-> {
//                    merchantMapper.selectAllMerchant(req);
//                });
//
//        //写法3
//        PageHelper.startPage(req.getPageNum(), req.getPageSize(), orderBy);
//        List<MerchantListResp> merchantListResps = super.baseMapper.selectAllMerchant(req);
//        PageInfo<MerchantListResp>  pageInfo3=new PageInfo<MerchantListResp>(merchantListResps);


        return pageInfo;
    }

    /**
     * 获取商户信息
     * @param id 商户ID
     * @return
     */
    @Override
    public MerchantInfoResp getMerchantInfo(Long id) {
        Merchant merchant = super.getById(id);
        if (ObjectUtil.isEmpty(merchant)) {
            throw new ApiException(500, "商户不存在");
        }
        MerchantInfoResp resp = MerchantConvert.INSTANCE.toMerchantInfoResp(merchant);
        //状态 1未激活 2开业中 3已过期     如果未激活，就不显示有效期
        if(!merchant.getActivate()){
            resp.setState(1);
            resp.setActivateTime(null);
            resp.setDisableTime(null);
        }else{
            if(resp.getDisableTime().after(new Date())){
                // 2开业中
                resp.setState(2);
            }else{
                //3已过期
                resp.setState(3);
            }
        }
        return resp;
    }

    /**
     * 商户备注列表
     * @param req
     * @return
     */
    @Override
    public PageInfo<MerchantRemark> getMerchantRemarkList(MerchantRemarkReq req) {
        PageInfo<MerchantRemark> pageInfo = PageHelper.startPage(req.getPageNum(), req.getPageSize(),"remark_time desc")
                .doSelectPageInfo(() -> {
                    LambdaQueryWrapper<MerchantRemark> queryWrapper = new LambdaQueryWrapper<>();
                    queryWrapper.eq(MerchantRemark::getMerchantId, req.getMerchantId());
                    merchantRemarkMapper.selectList(queryWrapper);
                });
        return pageInfo;
    }

    /**
     * 添加商户备注
     * @param merchantRemark
     * @return
     */
    @Override
    public int addMerchantRemark(MerchantRemark merchantRemark) {
        merchantRemark.setId(IdUtil.simpleUUID());
        merchantRemark.setRemarkTime(new Date());
        return this.merchantRemarkMapper.insert(merchantRemark);
    }

    /**
     * 删除商户备注
     * @param id
     * @return
     */
    @Override
    public int delete(String id) {
        return this.merchantRemarkMapper.deleteById(id);
    }

    /**
     * 获取商户详情(这里查询的是所有的业务)
     * @param merchantId
     * @return
     */
    @Override
    public MerchantResp getMerchantDetail(long merchantId) {

        MerchantResp merchantDetail = this.merchantMapper.findMerchantDetail(merchantId);
        List<Business> byBusinessService = businessConfigMapper.getByBusinessService();
        merchantDetail.setBusinessList(byBusinessService);
        return merchantDetail;
    }

    /**
     * 商户门店数量限制
     * @param id
     * @return
     */
    @Override
    public Integer selectStoreCount(Long id) {
        return this.merchantMapper.selectStoreCount(id);
    }
}
